// src/layouts/BasicLayout.jsx
import { useState, useEffect, useCallback } from 'react';
import { Layout, Menu, Input, Collapse, Button, Badge, Upload } from 'antd'; 
import { Link, useLocation, Outlet } from 'react-router-dom';
import './BasicLayout.css';
import { ReactComponent as CommunityIcon } from '../assets/社区.svg';
import { ReactComponent as SeedIcon } from '../assets/BT种子.svg';
import { ReactComponent as HomeIcon } from '../assets/首页.svg';
import { ReactComponent as UserIcon } from '../assets/用户.svg';
import { useNavigate } from 'react-router-dom';
import { LogoutOutlined, BellOutlined, UploadOutlined } from '@ant-design/icons';
import { fetchNotificationsNumService } from '../api/NotificationApi';
import CustomNotification from '../components/CustomNotification'; // 引入自定义通知组件
import { fetchAvailablePromotions } from '../api/PromotionApi'; // Adjust the import path

const { Header, Content, Footer } = Layout;
const BasicLayout = () => {
  const navigate = useNavigate();

  const [unreadCount, setUnreadCount] = useState(0);
  const [notificationVisible, setNotificationVisible] = useState(false);
  const [notificationContent, setNotificationContent] = useState('');
  
  const isLoggedIn = !!localStorage.getItem('token');

  useEffect(() => {
    if (isLoggedIn) {
      fetchNotificationsNumService()
        .then((data) => {
          setUnreadCount(data || 0);
        })
        .catch(() => setUnreadCount(0));
    }
  }, [isLoggedIn]);
  
  const { Panel } = Collapse;
  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('userId');
    navigate('/login');
  };
  const location = useLocation();
  
  const [promotionVisible, setPromotionVisible] = useState(true);
  const [promotions, setPromotions] = useState([]);
  const userId = localStorage.getItem('userId'); // Assuming you store userId in localStorage

  useEffect(() => {
    const getPromotions = async () => {
      try {
        const availablePromotions = await fetchAvailablePromotions();
        console.log('Fetched Promotions:', availablePromotions); // Log the fetched promotions
        setPromotions(availablePromotions.data[0]);
      } catch (error) {
        console.error('Failed to fetch promotions:', error);
      }
    };

    if (userId) {
      getPromotions();
    }
  }, [userId]);

  // 根据当前路径高亮菜单项
  const getSelectedKeys = useCallback(() => {
    if (location.pathname === '/') return ['1'];
    if (location.pathname.startsWith('/community')) return ['2'];
    if (location.pathname.startsWith('/seed')) return ['3'];
    if (location.pathname.startsWith('/user')) return ['4'];
    return ['1'];
  }, [location.pathname]);

  const menuItems = [
    {
      key: '1',
      label: <Link to="/">首页</Link>,
      icon: <HomeIcon />
    },
    {
      key: '2',
      label: <Link to="/community">社区</Link>,
      icon: <CommunityIcon/>
    },
    {
      key: '3',
      label: <Link to="/seed">种子中心</Link>,
      icon: <SeedIcon/>
    },
    {
      key: '4',
      label: <Link to="/user">用户</Link>,
      icon: <UserIcon />
    },
  ];

  // 搜索跳转
  const handleSearch = (value) => {
    if (value && value.trim()) {
      navigate(`/search?keyword=${encodeURIComponent(value.trim())}`);
    }
  };

  const handleImageUpload = async (event) => {
    const file = event.target.files[0];
    if (file) {
      // 重置通知状态
      setNotificationVisible(false);
      setNotificationContent('');

      // 这里可以添加重置其他状态的代码
      // 例如，清空 promotions 或者其他相关状态

      try {
        console.log("发送请求");
        const response = await fetch("https://api.trace.moe/search", {
          method: "POST",
          body: file,
          headers: { "Content-type": "image/jpeg" },
        });

        if (!response.ok) {
          throw new Error('网络响应不正常');
        }

        const data = await response.json();
        console.log(data); // 处理返回的数据

        if (data.result && data.result.length > 0) {
          const firstResult = data.result[0];
          const anilistId = firstResult.anilist;

          const query = `
          query ($id: Int) {
            Media(id: $id, type: ANIME) {
              id
              title {
                native
                romaji
                english
              }
              synonyms
            }
          }
          `;

          const variables = {
            id: anilistId
          };

          try {
            const response = await fetch("https://graphql.anilist.co", {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
              },
              body: JSON.stringify({
                query: query,
                variables: variables
              })
            });

            const data = await response.json();
            if (!response.ok) {
              throw new Error(`GraphQL Error: ${JSON.stringify(data.errors || data)}`);
            }

            setNotificationContent("正在搜索..."); // 显示正在搜索的通知
            setNotificationVisible(true); // 显示通知
            const nativeTitle = data.data.Media.title.native;
            setNotificationContent(`该图片来自于动漫: ${nativeTitle}`);
            
          } catch (error) {
            console.error("请求失败:", error);
            throw error;
          }
        } else {
          setNotificationContent('未找到相关信息');
          setNotificationVisible(true); // 显示通知
        }
      } catch (error) {
        console.error('图片上传失败:', error);
        setNotificationContent('图片上传失败，请重试');
        setNotificationVisible(true); // 显示通知
      }
    }
  };

  return (
    <Layout className="layout-container">
      <Header className="layout-header">
        <div className="layout-logo">BT7274</div>
        <Menu
          className="layout-menu"
          theme="dark"
          mode="horizontal"
          selectedKeys={getSelectedKeys()}
          items={menuItems}
        />
        <Input.Search
          placeholder="搜索..."
          className="layout-search"
          style={{ width: 250 }}
          onSearch={handleSearch}
        />
        <div>
          <input 
            type="file" 
            id="image-upload"
            accept="image/*"
            style={{ display: 'none' }}
            onChange={handleImageUpload}
          />
          <Button 
            icon={<UploadOutlined />}
            onClick={() => document.getElementById('image-upload').click()}
          >
            动漫识图
          </Button>
        </div>
        {isLoggedIn && (
          <Badge count={unreadCount} offset={[0, 5]}>
            <Button
              icon={<BellOutlined />}
              className="notification-button"
              style={{ marginLeft: '10px' }}
              onClick={() => navigate('/notifications')}
            />
          </Badge>
        )}
        {isLoggedIn && userId ? (
          <Button
            icon={<LogoutOutlined />}
            onClick={handleLogout}
            className="logout-button"
          >
            登出
          </Button>
        ) : (
          <Button
            onClick={() => navigate('/login')}
            className="login-button"
          >
            登录
          </Button>
        )}
      </Header>
      
      <CustomNotification 
        visible={notificationVisible} 
        title={notificationContent} 
        onClose={() => setNotificationVisible(false)} 
      />
      {/* 促销活动栏 */}
      {promotionVisible && (
                <div className="promotion-section">
                  <Collapse defaultActiveKey={['1']} className="promotion-collapse">
                    <Panel header="促销活动" key="1">
                      <div className="promotion-content">
                        <p>{promotions.title}</p>
                        <p>开始时间: {new Date(promotions.startTime).toLocaleString()}</p>
                        <p>结束时间: {new Date(promotions.endTime).toLocaleString()}</p>
                      </div>
                    </Panel>
                  </Collapse>
                </div>
              )}
      <Content className="layout-content">
        <div className="layout-main-content">
          <Outlet />
        </div>
      </Content>
      <Footer className="layout-footer">
        BT7274 ©{new Date().getFullYear()} Created by BT7274
      </Footer>
    </Layout>
  );
};

export default BasicLayout;